<?php
namespace app\index\controller;

use think\Controller;
use think\Db;

class Earnings extends Base
{
    public function index()
    {

        //用户信息
        $user = Db::name('user')->field('earnings,take_money,money')->where('id', $this->uid)->find();

        //邀请总和
        $son = Db::name('user')->where('pid=' . $this->uid . ' or ppid=' . $this->uid)->count();

        //累计收益数目
        $total = Db::name('earnings')->where('uid', $this->uid)->count();

        $start = strtotime('today');
        $end = $start + 86400;

        //今日收益
//        $earnings1 = Db::name('order')
//            ->where(['pid' => $this->uid, 'status' => 1])
//            ->where("pay_time>=$start AND pay_time <$end")
//            ->sum('commission1');
//        $earnings2 = Db::name('order')
//            ->where(['ppid' => $this->uid, 'status' => 1])
//            ->where("pay_time>=$start AND pay_time <$end")
//            ->sum('commission2');
        $start = strtotime('today');
        $end = $start + 86400;

        //今日收益
        $today_earnings = Db::name('earnings')
            ->where('uid', $this->uid)
            ->where("create_time>=$start AND create_time <$end")
            ->sum('money');

        $total_earnings = Db::name('earnings')
            ->where('uid', $this->uid)
            ->sum('money');

        //本月预估收益
        $days = date('d');

        $month_earnings = round($total_earnings / $days * 30, 2);

        //最高收益 %
        $top_earnings = Db::name('user_sales')->order('commission1 desc')->value('commission1');

        //会员等级
        $user_level = Db::name('user_sales')->field('sales_name,id,commission1')->order('commission1 asc')->select();

        //收益说明
        $help = Db::name('help')->where(['type'=>3,'status'=>1])->value('content');

        $this->assign('help', $help);
        $this->assign('user_level', $user_level);
        $this->assign('top_earnings', $top_earnings);
        $this->assign('month_earnings', $month_earnings);
        $this->assign('today_earnings', $today_earnings);
        $this->assign('total', $total);
        $this->assign('user', $user);
        $this->assign('son', $son);
        return $this->fetch();
    }


    //待领取收益
    public function waitProfit()
    {

        //用户信息
        $user = Db::name('user')->alias('a')
            ->field('a.earnings,a.level,b.commission1')
            ->leftJoin('user_sales b', 'a.sales=b.id')
            ->where('a.id', $this->uid)
            ->find();

        //最高等级
        $top_earnings = Db::name('user_sales')->field('id,commission1,commission2')->order('commission1 desc')->find();

        $top_level = $user['earnings'];

        if ($user['level'] == 0) {
            $user['commission1'] = 10;
        }
        //股东可领取收益
        if ($top_earnings && $user['level'] != $top_earnings['id']) {

            $top_level = $user['earnings'] / $user['commission1'] * $top_earnings['commission1'];
        }

        //收益说明
        $help = Db::name('help')->field('id,content')->where(['type' => 4, 'status' => 1])->order('id desc')->find();


        $this->assign('top_earnings', $top_earnings);
        $this->assign('top_level', $top_level);
        $this->assign('help', $help);
        $this->assign('user', $user);

        return $this->fetch();
    }


    //收益列表
    public function getEarningsList()
    {

        $uid = $this->uid;

//        $where = '(a.pid=' . $uid . ' OR a.ppid=' . $uid . ') AND a.status=1';

//        $list = Db::name('order')->alias('a')
//            ->field('a.total_fee,a.commission1,a.commission2,a.pid,a.ppid,a.pay_time,b.nickname')
//            ->leftJoin('user b', 'a.uid=b.id')
//            ->where($where)->order('a.id desc')
//            ->paginate(15)->each(function ($item, $key) {
//                $item['pay_time'] = date('Y-m-d H:i', $item['pay_time']);
//                return $item;
//            });;

        $list = Db::name('earnings')->alias('a')
            ->field('a.*,b.nickname')
            ->where('a.uid', $uid)
            ->leftJoin('user b', 'a.pay_uid=b.id')
            ->order('a.id desc')
            ->paginate(15)->each(function ($item, $key) {
                $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                return $item;
            });;

//            return $list;
        return ['code' => 1, 'data' => $list, 'uid' => $uid];
    }

    //领取收益
    public function gainMoney()
    {

        if ($this->userInfo['earnings'] == 0) {
            $this->error('当前没有可领取收益');
        }

        $upd = Db::name('user')
            ->where('id', $this->uid)
            ->inc('money', $this->userInfo['earnings'])->exp('earnings', 0)
            ->update();

        if ($upd) {
            $this->success('领取成功');
        } else {
            $this->error('领取失败');
        }
    }

    //用户余额
    public function wallet()
    {
        $user = $this->userInfo;
        $this->assign('user', $user);


        $start = strtotime('today');
        $end = $start + 86400;

        //今日收益
        $today_earnings = Db::name('earnings')
            ->where('uid', $this->uid)
            ->where("create_time>=$start AND create_time <$end")
            ->sum('money');

        $this->assign('today_earnings', $today_earnings);

        return $this->fetch();
    }

    //提现
    public function takeMoney()
    {

        if (request()->isPost()) {

            $data = input('post.');

            if ($data['type'] == 2) {
                //支付宝提现

                if (empty($data['account_num'])) {
                    $this->error('请输入支付宝账号');
                }

                if (empty($data['real_name'])) {
                    $this->error('请输入真实姓名');
                }
            } else {

                if (empty($this->userInfo['wx_openid'])) {

                    $this->error('微信未授权');
                }

                $data['account_num'] = $this->userInfo['wx_openid'];
                $data['real_name'] = $this->userInfo['nickname'];
            }


            if (empty($data['money']) || $data['money'] < 0) {
                $this->error('请输入提现金额');
            }

            if ($data['money'] > $this->userInfo['money']) {
                $this->error('账户余额不足');
            }

            if ($data['money'] % 10 > 0) {
                $this->error('提现金额需为10的倍数');
            }

            $start = strtotime('today');
            $end = $start + 86400;

            //一天只能提现一次
            $take = Db::name('take_money')
                ->where('uid', $this->uid)
                ->where('status', '<', 2)
                ->where('create_time', 'between', "$start,$end")
                ->find();

            if ($take) {
                $this->error('每日只能申请一次');
            }

            $addData = array(
                'type' => $data['type'],
                'uid' => $this->uid,
                'money' => $data['money'],
                'account_num' => $data['account_num'],
                'real_name' => $data['real_name'],
                'status' => 0,
                'notes' => '审核中',
                'create_time' => time()
            );

            Db::startTrans();

            $add = Db::name('take_money')->insert($addData);

            if ($add) {

                $upd = Db::name('user')->where('id', $this->uid)->setDec('money', $data['money']);

                if ($upd) {
                    Db::commit();
                    $this->success('申请成功');

                } else {
                    Db::rollback();
                    $this->error('申请失败');
                }

            } else {

                Db::rollback();
                $this->error('申请失败');
            }
        }

        $money = $this->userInfo['money'];

        $wx = Db::name('user')->field('wx_openid,wx_nickname,wx_avatar')->where('id', $this->uid)->find();

        //支付宝账号
        $alipay = Db::name('take_money')->field('account_num,real_name')->where(['uid' => $this->uid, 'type' => 2])->find();

        $this->assign('money', $money);
        $this->assign('alipay', $alipay);
        $this->assign('wx', $wx);
        return $this->fetch();
    }

    //提现记录
    public function takeMoneyRecord()
    {

        $list = Db::name('take_money')
            ->where(['uid' => $this->uid])
            ->order('id desc')
            ->paginate(15)->each(function ($item, $key) {
                $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                return $item;
            });;

//            return $list;
        return ['code' => 1, 'data' => $list];
    }

    //收益排行榜
    public function ranking()
    {

        //收益总排行
        $total_tops = Db::name('user')->field('nickname,avatar,total_earnings,level')->order('total_earnings desc,id asc')->limit(10)->select();

        //今日排行
        $today_start = strtotime('today');
        $today_end = $today_start + 86400;

        $today_tops = Db::name('earnings')->alias('a')
            ->leftJoin('user b', 'a.uid=b.id')
            ->field('sum(a.money) as money,a.uid,b.avatar,b.nickname,b.level')
            ->where('a.create_time', 'between', "$today_start,$today_end")
            ->group('a.uid')
            ->order('money desc')
            ->select();

        //昨日排行
        $yesterday_start = $today_start - 86400;
        $yesterday_end = $today_start;

        $yesterday_tops = Db::name('earnings')->alias('a')
            ->leftJoin('user b', 'a.uid=b.id')
            ->field('sum(a.money) as money,a.uid,b.avatar,b.nickname,b.level')
            ->where('a.create_time', 'between', "$yesterday_start,$yesterday_end")
            ->group('a.uid')
            ->order('money desc')
            ->select();

        $level = Db::name('user_level')->field('id,level_name')->column('level_name', 'id');

        $this->assign('level', $level);
        $this->assign('total_tops', $total_tops);
        $this->assign('today_tops', $today_tops);
        $this->assign('yesterday_tops', $yesterday_tops);

        return $this->fetch();
    }

}
